<?php

$self   = $_SERVER['PHP_SELF'];

require_once("db_login_test.php");
require_once("DB.php");
	
$cnx = connect_to_db();

if (!$cnx) {
	header('Status: 500 No Database Connection');
	die("Couldn't connect to the database!");
}

if ($HTTP_POST_VARS['submit']) {

	// Check the authorization key
	if (strcmp($HTTP_POST_VARS['auth'], "a457c19eef") != 0) {
		
		//header('HTTP/1.1 400 Bad Authentication');
		header("Status: 400 Bad Authentication");
		
		echo "Bad Authentication";
		exit();
	} 

	// Get the user ID
	global $user_id;
	$user_id = $HTTP_POST_VARS['user_id'];

	// See if this is a log
	if (isset($HTTP_POST_VARS['log'])) {
		$log_data = $HTTP_POST_VARS['log'];
			
		$log_query = "UPDATE user SET last_log_time=(DATE_ADD(NOW(),INTERVAL 2 HOUR)) WHERE user_id=$user_id";
		$log_res   = $cnx->query($log_query);
		exit();
	}


	// Get the glucose reading
	if ( isset($HTTP_POST_VARS['glucose']) ) {
		$glucose_reading = $HTTP_POST_VARS['glucose'];
		
		if (strcmp($glucose_reading,"9999") == 0) {
			$glucose_reading="NULL";
		}
		
	}
	else {
		header('Status: 500 Don\'t understand format');
		echo "Don't understand format (no glucose found)";
		exit();
	}
	
	
	// Need to actually process pre-tags here!
	if ( isset($HTTP_POST_VARS['tags']) ) {
		$tag_str = $HTTP_POST_VARS['tags'];
		$tags = explode(";", $tag_str);
		error_log("tag_str is $tag_str");
		
	}
	else {
		header('Status: 500 Don\'t understand format');
		echo "Don't understand format (no pre_tags found)";
		exit();
	}
	
	
	// Process activity type
	if ( isset($HTTP_POST_VARS['activity_type']) ) {
		$activity_type = $HTTP_POST_VARS['activity_type'];
		
	}
	else {
		header('Status: 500 Don\'t understand format');
		echo "Don't understand format (no activity type found)";
		exit();
	}
	
	if (strcmp($activity_type, "Meal") == 0) {
		if ( isset($HTTP_POST_VARS['meal_descriptor']) ) {
			$meal_descriptor = $HTTP_POST_VARS['meal_descriptor'];
			$meal_data = explode(";", $meal_descriptor);
			$activity_type = "MEAL";		
		
		} else {
			header('Status: 500 Don\'t understand format');
			echo "Don't understand format (no meal descriptor found)";
			exit();
		}	
	
	} else if (strcmp($activity_type, "Exercise") == 0)  {
		
		if ( isset($HTTP_POST_VARS['exercise_descriptor']) ) {
			$exercise_descriptor = $HTTP_POST_VARS['exercise_descriptor'];
			$exercise_data = explode(";", $exercise_descriptor);		
			$activity_type = "EXERCISE";
		
		} else {
			header('Status: 500 Server Error');
			echo "Don't understand format (no exercise descriptor found)";
			exit();
		}		
		
	
	} else if (strcmp($activity_type, "Other") == 0)  {
		$activity_type = "OTHER";
	
	} else {
		header('Status: 500 Don\'t understand format');
		echo "Don't understand format (unrecognized activity type)";
		exit();
	}
	
// ELSE must create an experience sample for user here !

	start_transaction("sample");

	$query1 = "INSERT INTO sample (time, user_id, activity_type, glucose,user_comment,cp_comment) VALUES " .
			  "(DATE_ADD(NOW(),INTERVAL 2 HOUR), $user_id, \"$activity_type\", $glucose_reading, NULL, NULL)";
	$res = $cnx->query($query1);
	
	if (DB::isError($res)) {
		
		header("Status: 500 " . DB::errorMessage($res)); 
		end_transaction("sample");
		die("Error while adding sample to database (1)! " . " " . $query1 . " " . DB::errorMessage($res));
	}
	
	$query2 = "SELECT MAX(sample_id) FROM sample";
	$res = $cnx->query($query2);
	
	if (DB::isError($res)) {
		
		header("Status: 500 " . DB::errorMessage($res));
		end_transaction("sample"); 
		die("Error while finding max id!". DB::errorMessage($res));
	}

	end_transaction("sample");

	$q_data = $res->fetchRow();
	$this_sample_id = $q_data[0];	
	
	mkdir("samples_test/sample_".$this_sample_id, 0755);
	mkdir("samples_test/sample_".$this_sample_id."/image", 0755);
	mkdir("samples_test/sample_".$this_sample_id."/audio", 0755);

	//echo "GOT THE FOLLOWING FILES: <br />";
	$num_valid_files = 0;
	foreach ($HTTP_POST_FILES as $name => $data) {
		//echo "Upload name is $name and temp name is " . $data["tmp_name"] . "<br />";

		$type_as_lower = strtolower($data["type"]); 

		if ( !(strpos($type_as_lower,"amr") === FALSE) ) {
			$num_valid_files++;
			process_audio_file($data, $this_sample_id);
		}
		else if ( !(strpos($type_as_lower,"jpeg") === FALSE) ) {
			$num_valid_files++;
			process_image_file($data, $this_sample_id);
		}
		else {
			header("Status: 500 Unsupported Data Type");
			exit();
		}
	}
	
	/*
	// run the script that will convert the AMR -> MP3
	system("/home/moddwebc/usr/local/bin/mp3_create sample_".$this_sample_id);
	*/
	
	switch($activity_type) {
		case "EXERCISE":
			$res = $cnx->query("INSERT INTO exercise (sample_id, calories, time) " . 
							"VALUES ($this_sample_id, $exercise_data[0], $exercise_data[1])");
			if (DB::isError($res)) {
				//header("HTTP/1.1 500 Bad things", true, 500); 
				//exit();
				header("Status: 500 " . DB::errorMessage($res)); 
				die("Error while adding exercise info to database!". DB::errorMessage($res));
			}
			break;
		
		case "MEAL":
			$res = $cnx->query("INSERT INTO meal (sample_id, carbohydrates, fat, protein) " . 
							"VALUES ($this_sample_id, $meal_data[0], $meal_data[1], $meal_data[2])");
			if (DB::isError($res)) {
				header("Status: 500 " . DB::errorMessage($res)); 
				die("Error while adding meal info to database!". DB::errorMessage($res));
			}
			break;	
	
	} 
	error_log("gonna update tags");
		
	update_tags($tags);
	
	echo("ID:".$this_sample_id);
	
}


else {

	render_header();
	render_start();


	echo ('
	<form action="' . $self . '" method="POST" enctype="multipart/form-data">
	<br /><br />
	
	<input type="file" name="upload_file" />
	<br />
	<input type="submit" name="submit" value="submit" />
	<input type="hidden" name="user_id" value="4" />
	<input type="hidden" name="auth" value="a457c19eef" />
	<input type="hidden" name="glucose" value="9999" />
	<input type="hidden" name="activity_type" value="Exercise" />
	<input type="hidden" name="exercise_descriptor" value="2;3" />
	<input type="hidden" name="tags" value="once;yucky" />

	</form>
	');
	
	
	/*
	echo ("<h3> The Images! </h3>");
	$query = "SELECT * FROM image";				
	$res = mysql_query($query);
	
	while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
		$img_path = $row['location'];
		
		echo "<img src=\"$img_path\"><br /> <br />";
	}
	*/
	
	render_end();
}


// ADDED
//exit();

function start_transaction($table_name) {
	//echo "STARTING TRANSACTION";
	global $cnx;
	$cnx->autoCommit(false);
	$cnx->query("LOCK TABLES ".$table_name." WRITE");
}

function end_transaction($table_name) {
	//echo "ENDING TRANSACTION";
	global $cnx;
	$cnx->commit();
	$cnx->autoCommit(true);
	$cnx->query("UNLOCK TABLES");
}


function process_image_file($file_data, $sample_id) {
	
	global $cnx;
	
	//echo "GOT " . print_r($file_data) . "<br />";
	//echo "ID HERE IS $sample_id <br />";
	
	start_transaction("image");
	// need to figure out what the next id would be
	$query = "SELECT MAX(image_id) FROM image";
	$res = $cnx->query($query);

	$q_data = $res->fetchRow();
	if ($q_data[0]) {
		$max_id = $q_data[0];
	} else {
		$max_id = 0;
	}
	
	$next_id = $max_id + 1;
	//echo "next_id is $next_id <br />";
	
	$new_filename = "image_" . $next_id . ".jpg";
	
	$contents = file_get_contents($file_data['tmp_name']);
	
	
	$fhandle = fopen("samples_test/sample_".$sample_id."/image/".$new_filename, 'w');
	$write_res = fwrite($fhandle, base64_decode($contents));
	if ($write_res === FALSE) {
		header("Status: 500 " . "Couldn't write image to file" );
		exit();
	}
	else {
		
		fclose($fhandle);
	
		//copy($file_data['tmp_name'], "modd_photos/" . $new_filename);
		//echo "GOT FOR PUT_RES! $put_res<br />";
	
		//$query = 'INSERT INTO image (image_id,sample_id,location) VALUES '.
		//'(NULL,'.$sample_id.',"samples/sample_'.$sample_id.'/image/'.$new_filename.'")';				
		
		$query = 'INSERT INTO image (image_id,sample_id,location) VALUES '.
		'('.$next_id.','.$sample_id.', "'.$new_filename.'")';
		
		//echo "QUERY IS <br />" . $query . "<br />OK!";
		
		$res = $cnx->query($query);
		//echo "GOT FOR INSERT RES " . print_r($res) . "<br />";
	}
	
	end_transaction("image");
}



function process_audio_file($file_data, $sample_id) {
	
	global $cnx;
	
	//echo "GOT " . print_r($file_data) . "<br />";
	//echo "ID HERE IS $sample_id <br />";
	
	start_transaction("audio");
	
	// need to figure out what the next id would be
	$query = "SELECT MAX(audio_id) FROM audio";
	$res = $cnx->query($query);

	$q_data = $res->fetchRow();
	if ($q_data[0]) {
		$max_id = $q_data[0];
	} else {
		$max_id = 0;
	}
	
	$next_id = $max_id + 1;
	//echo "next_id is $next_id <br />";
	
	$new_amr_filename = "audio_" . $next_id . ".amr";
	
	$contents = file_get_contents($file_data['tmp_name']);
	
	
	$fhandle = fopen("samples_test/sample_".$sample_id."/audio/".$new_amr_filename, 'w');
	$write_res = fwrite($fhandle, base64_decode($contents));
	if ($write_res === FALSE) {
		header("Status: 500 " . "Couldn't write audio to file" );
		exit();
	}
	else {
		
		fclose($fhandle);
	
		//copy($file_data['tmp_name'], "modd_photos/" . $new_filename);
		//echo "GOT FOR PUT_RES! $put_res<br />";
	
		//$query = 'INSERT INTO image (image_id,sample_id,location) VALUES '.
		//'(NULL,'.$sample_id.',"samples/sample_'.$sample_id.'/image/'.$new_filename.'")';				
		
		$query = 'INSERT INTO audio (audio_id,sample_id,location) VALUES '.
		'('.$next_id.','.$sample_id.', "'.$new_amr_filename.'")';
		
		//echo "QUERY IS <br />" . $query . "<br />OK!";
		
		$res = $cnx->query($query);
		//echo "GOT FOR INSERT RES " . print_r($res) . "<br />";
	}
	
	end_transaction("audio");
}

function render_header() {
	echo ('<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
			<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
			<title>ModdWeb Uploader</title>
			</head>'
	);
}

function render_start() {
	echo ('<body>

		<h2> Welcome to MoDD </h2>
		<p> This form can be used for uploading samples. </p>
		');
}

function render_end() {
	echo ('</body></html>');

}

function update_tags($pre_tag_list) {

	error_log("in update tags");
	error_log("pre tag list is . $pre_tag_list");
	

	global $cnx, $user_id, $this_sample_id;
	
	
	foreach ($pre_tag_list as $tag) {
	     error_log("tag here is " . $tag);
		$res = $cnx->query("SELECT tag_id FROM tag WHERE text=\"$tag\"");
		
		start_transaction("tag");
		// if this is a new tag
		if ($res->numRows() == 0) {
			$cnx->query("INSERT INTO tag (user_id, text, uses) VALUES ".
						"($user_id, \"$tag\", 1)");
						
			$res = $cnx->query("SELECT MAX(tag_id) FROM tag");
	
			$q_data = $res->fetchRow();
			$tag_id = $q_data[0];	
				
				
		} else {
			$q = $res->fetchRow();
			$tag_id = $q[0];
			$cnx->query("UPDATE tag SET uses=uses+1 WHERE tag_id=$tag_id");	
		}
		end_transaction("tag");
		
		$cnx->query("INSERT INTO sample_tag (sample_id, tag_id) " . 
						"VALUES ($this_sample_id, $tag_id)");
	}
}

?>